using System;
using System.Collections.Generic;
using System.Text;

namespace Pixysoft.IO
{
    public class ByteLineReader
    {
        private byte[] msg = null;

        private int position = -1;


        private ByteLineReader() { }

        public ByteLineReader(byte[] msg)
        {
            if (msg == null)
                throw new Exception();

            this.msg = msg;

            position = 0;
        }

        public byte[] ReadLine()
        {
            if (position >= msg.Length)
                return null;

            ByteBuilder builder = new ByteBuilder();

            byte preChar = byte.MinValue;
            byte curChar = byte.MinValue;

            for (int i = position; i < msg.Length; i++)
            {
                byte c = msg[i];

                if (preChar == byte.MinValue)
                    preChar = c;
                else
                    preChar = curChar;

                curChar = c;

                builder.Append(c);

                position++;

                if (preChar == (byte)'\r' && curChar == '\n')
                {
                    builder.Remove(builder.Length - 2, 2);

                    break;
                }

            }

            return builder.ToByte();

        }

        public byte[] ReadAll()
        {
            if (position >= msg.Length)
                return null;

            ByteBuilder builder = new ByteBuilder();

            for (int i = position; i < msg.Length; i++)
            {
                byte c = msg[i];

                builder.Append(c);

                position++;
            }

            return builder.ToByte();
        }

        public bool HasMore
        {
            get
            {
                return position >= 0 && position <= msg.Length - 1;
            }
        }

        private void test()
        {
            string value = "123\r\n456\r\n789";

            ByteLineReader reader = new ByteLineReader(Pixysoft.StringCoder.StringToByte(value));

            Console.WriteLine(Pixysoft.StringCoder.ByteToString(reader.ReadLine()));
            Console.WriteLine(Pixysoft.StringCoder.ByteToString(reader.ReadLine()));
            Console.WriteLine(Pixysoft.StringCoder.ByteToString(reader.ReadLine()));
        }
    }
}
